﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DotNet.Random.ResourceService
{
    class StatisticsAddress
    {
        public List<AddressModel> GetAddressList20111031()
        {
            var list = new List<AddressModel>();
            string str = GetAddressList();
            var data = System.Text.RegularExpressions.Regex.Split(str, "<br>");
            var count = 0;
            foreach (var item in data)
            {
                var temp = System.Text.RegularExpressions.Regex.Split(item, "\\s")
                    .Where(d => d != "").ToList();
                if (temp.Count > 0)
                {
                    list.Add(new AddressModel() { id = count, num = temp[0], address = temp[temp.Count - 1] });
                    count++;
                }
            }
            return list;
        }

        public string GetAddress(string url, string path)
        {
            var res = "";
            try
            {
                var web = new System.Net.WebClient();
                var str = web.DownloadString(url);
                if (!string.IsNullOrEmpty(str))
                {
                    var doc = new HtmlAgilityPack.HtmlDocument();
                    doc.LoadHtml(str);
                    var node = doc.DocumentNode.SelectSingleNode(path);
                    res = (node != null ? node.InnerHtml : "");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return res;
        }

        #region protected method
        
        protected string GetAddressList()
        {
            var url = "http://www.stats.gov.cn/tjbz/xzqhdm/t20120105_402777427.htm";
            var path = "/html/body/table[2]/tr/td/table/tr/td/table/tr/td/table/tr[3]/td/table[2]/tr/td/span";
            var res = GetAddress(url, path).Replace("&nbsp;", "");
            return res;
        }

        #endregion
    }

    public class AddressModel
    {
        public int id { get; set; }

        public string num { get; set; }

        public string address { get; set; }
    }
}
